<?php
namespace routes;
use app\compute\tree\TrieController;
use app\console\book\BookController;
use app\console\demo\controllers\testController;
use app\console\elasticsearch\ElasticsearchController;
use app\console\tool\controllers\FaceToolController;
use app\console\tool\controllers\modelController;
use app\console\tool\controllers\PropertyController;
use db\factory\soft_db;
use db\model\model_auto\model_auto;
use db\model\user\user;
use extend\awesome\awesome_driver_rabbitmq;
use extend\awesome\awesome_echo_tool;
use GuzzleHttp\Client;
use Pc\Utils\Utility;
use request\request;
use system\cache\cache;
use system\common;
use system\encrypt;
use system\excel;
use system\http;
use system\mail;
use task\TimeTask\command\command;

routes::cli("model/create/{table}",modelController::class."@create");
routes::cli("start",function (){
    echo microtime(true)-start_at;
});
routes::cli("cli",function (user $user){
    print_r($user->limit(1,1)->all());
});
routes::cli("test",'testController'."@index");
routes::cli("email",function (mail $mail){
    $mail->send_email("1293777844@qq.com","dasda","dasd");
});
routes::cli('faced', FaceToolController::class . '@solveFaced');
routes::cli("echo/{name}",function (request $request){
    print_r($request->all());die();
    while (1)
    echo microtime(true).PHP_EOL;
});

routes::cli("company",function (t_company $company){
    $data=$company->select(["id","name","pid",'layer'])->all();
    function compile_menu(array $menu_list,int $pid=0,int $layer=2){
        $result=[];
        foreach ($menu_list as $item){
            if($item['pid']==$pid){//
                $children=compile_menu($menu_list,$item['id']);
                if(!empty($children)){
                    $item['children']=$children;
                }
                $result[]=$item;
            }
        }
        return $result;
    }
    $data=compile_menu($data,0);
    print_r($data);
});
routes::group(function (){

},[],"test/");
routes::cli("explode",function (){
    print_r(explode('文',"中文 符号"));
});
routes::cli("book1586377",BookController::class."@index")->tick("2021-04-30",60*2);
//routes::cli("loadTask",function (mail $mail){
//    $mail->send_email("1293777844@qq.com","test","test");
//})->tick("2021-05-01 00:00:00",60);
routes::cli("decrypt",function (){
    echo "load".PHP_EOL;
    echo encrypt::ras_encrypt_private("OFnUhlXDjr8WTAtqH0EZc65YemCGRzB@");
});
routes::cli("version",function () {
    return version_compare("1.2021.1030.617", "1.2021.1025.524")===1;
});
routes::cli("faker",function (){
    $model=model_auto::model("ent_client_hard_disk_capacity_warning");
    $data=[];
    for ($i=0;$i<1000000;$i++){
        $data[]=[
            'cid'=>rand(1,300),
            'type'=>rand(0,1)
        ];
        if (count($data)>1500){
            echo $i.PHP_EOL;
            $model->create($data);
            $data=[];
        }
    }
    return $model->count();
});
routes::cli("cache",function (awesome_echo_tool $tool){
   return $tool->get_online_users();
});
routes::cli('fixedData',function (){
    $warningModel=model_auto::model('ent_client_hard_disk_capacity_warning');
    $model=clone $warningModel;
    $cids=array_column($warningModel->select(['cid'])->all(),'cid');
    $clientInfo=model_auto::model('ent_client')
        ->where_in('id',$cids)
        ->all();
    $clientInfo=common::array_group_by_key($clientInfo,'id');
    $deptInfo=soft_db::table("ent_client_group")
        ->select("cid","dept_id,name")
        ->where_in('cid',$cids)
        ->join("ent_dept",'id','dept_id')
        ->whereString("delete_date is null")
        ->get();
    $deptInfo=common::array_group_by_key($deptInfo,'cid');
    foreach ($cids as $cid){
        (clone $model)
            ->where('cid',$cid)
            ->update([
                'client_name'=>$clientInfo[$cid][0]['client_name'],
                'computer_name'=>$clientInfo[$cid][0]['computer_name'],
                'remark'=>$clientInfo[$cid][0]['remark'],
                'dept_id'=>empty($deptInfo[$cid])?0:$deptInfo[$cid][0]['dept_id'],
                'dept_name'=>empty($deptInfo[$cid])?'未分组':$deptInfo[$cid][0]['name'],
            ]);

    }
});
routes::cli('times',function (){
    return date('Y-m-t');
});
routes::cli('matchNum',function (){
   var_dump(round(99.99,0)==100);
});
routes::cli('test122',function (){
    return model_auto::model('ent_client_hard_disk_capacity_warning')->ReadMaster()->first_cache()
        ->count();
});
routes::cli("timetest",function (){
   return date('Y-m-d',strtotime("+15 day 2021-08-03"));
});
routes::cli("sql-test",function (){
    return soft_db::table('ent_user')
        ->select("name")
        ->or_where('user','赵李杰')
        ->get();
});
routes::cli('cache-',function (cache $cache){
    return $cache->get_non_exist_set('jjawesome',function (request $request) {
        return microtime(true);
    },3);
});

//routes::cli('jjawesome',function (){
//    echo "load".PHP_EOL;
//    sleep(10);
//})->tick("2021-07-02",5);

routes::cli('time-compute',function (){
   $day =  common::get_diff_time(strtotime(date('Y-m-d')),strtotime('2022-02-19'));
   $day = str_replace('天','',$day);
   return ((intval($day)+1)/365)*10;

});

routes::cli('roi', function (){
    $template = <<<template
    'roi_jihuo' => [
            'name'    => '新增设备ROI',
            'type'    => 'text',
            'order_type' => 'desc',
            'display' => '+list,+edit,-search,+detail',
        ],
        'roi_jihuo_compensatereal' => [
            'name'    => '新增设备ROI（实际赔付）',
            'type'    => 'text',
            'order_type' => 'desc',
            'display' => '+list,+edit,-search,+detail',
        ],
        'roi_jihuo_compensateestimate_withdraw' => [
            'name'    => '新增设备ROI（预估赔付+提现）',
            'type'    => 'text',
            'order_type' => 'desc',
            'display' => '+list,+edit,-search,+detail',
        ],
        'roi_jihuo_compensatereal_withdraw' => [
            'name'    => '新增设备ROI（实际赔付+提现）',
            'type'    => 'text',
            'order_type' => 'desc',
            'display' => '+list,+edit,-search,+detail',
        ],
        'roi_jihuo_4_day' => [
            'name'    => '新增设备ROI(近4日)',
            'type'    => 'text',
            'order_type' => 'desc',
            'display' => '+list,+edit,-search,+detail',
        ],
        'roi_jihuo_4_day_compensateestimate' => [
            'name'    => '新增设备ROI（近4日+预估赔付）',
            'type'    => 'text',
            'order_type' => 'desc',
            'display' => '+list,+edit,-search,+detail',
        ],
template;
    preg_match_all("/'roi_(.*?)'/is", $template, $matchs, PREG_SET_ORDER);
    foreach ($matchs as $match) {
        echo $match[0]. ',' . PHP_EOL;
    }
});
routes::cli('radio-compute', function (){
    $tem = file_get_contents(DIR_PATH . '/filesystem/log/template.txt');
    $temData = explode(';', $tem);
    $result = '<?php
    ';
    foreach ($temData as $datum) {
        $datum = trim($datum);
        if (empty($datum)) {
            continue;
        }
        preg_match_all("/row\['(.*)?'\] = /", $datum, $match, PREG_SET_ORDER);
        $key = $match[0][1];
        $datum = preg_replace("/row\['(.*)?'\] = /", 'row = ', $datum) . ';';
        $datum = preg_replace('/\$row\[\'(.*?)\'\\]/', "'\\1'", $datum);
        $datum = preg_replace("/'(.*?)' ([\+|\-]?) '(.*?)',/", "'\\1 \\2 \\3',", $datum);
        $datum = preg_replace("/'(.*?)' ([\*|\/]?) (.*?),/", "'\\1 \\2 \\3',", $datum);
        $datum = preg_replace('/computePercent\(/', 'computePercentByCondition(' . PHP_EOL . '$row,' . PHP_EOL . "'{$key}'," . PHP_EOL . '$keyPrefix,', $datum);
        $result .= $datum;
    }
    file_put_contents(DIR_PATH . '/filesystem/log/res.php', $result);
});
routes::cli('z' , function () {
    var_dump(round(('0.0000'/'1012.5600' - 1) * 100));
});
routes::cli('z-test', function (){
    var_dump(preg_match('/^[a-z|A-Z|0-9]+$/u', 'jjawes-ome'));
});

routes::cli('access-token', function (){
    return base64_decode('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODc4N1wvYXBpXC93ZWJcL2xvZ2luXC9sb2dpbiIsImlhdCI6MTY3NTgyMzM1NiwiZXhwIjoxNjc4NDE1MzU2LCJuYmYiOjE2NzU4MjMzNTYsImp0aSI6InpQZmQ0Q3lnZE45WnpIeDMiLCJzdWIiOjEsInBydiI6ImE0YzQ4OGE5MDcwZDMwNTFlYzgyZWFiYzliYTZjZGYyMWVkNjU1M2MiLCJkZXZpY2VfaGFzaCI6IkR1dzJPSlZ5aU5KQkIxaUgrNHU5b1E9PSJ9.DX6D1dPmXSr7TFBmj3ZR23ehERNYObt5OLivH6p6Ie0');
});

routes::cli('md5-1', function (){
    <<<json

json;

    <<<json
[
        {
            "tplus":1,
            "value":"2",
            "app":"a"
        
        },
        {
         "tplus":2,
            "value":"2"
        
        }
    ]
json;


    return md5('jjawesome-test');
});

routes::cli('cache-test', function (cache $cache){
   return $cache->get_non_exist_set('test-key', function (){
       echo "生成cache" . PHP_EOL;
       return date('Y-m-d');
   }, 10);
});

routes::cli('android-test', function (){
    $sql = <<<excel
新增日期 date_new
产品 app
产品类型 app_type
广告消耗 toutiao_cost_new__valuefromdetailday1
新增设备数 process_start_cnt_open__valuefromdetailday1
新增设备成本 cost_device_jihuo__ext
总广告收入 income_calibrate_open__sumfromdetailallday
预估赔付 compensateestimate_new__valuefromdetailday1
总提现金额 withdraw_money_open__sumfromdetailallday
首日广告收入 income_calibrate_open__valuefromdetailday1
首日提现金额 withdraw_money_open__valuefromdetailday1
首日ROI roi_day1__ext
首日ROI（预估赔付） roi_compensateestimate_day1__ext
首日ROI（预估赔付+提现） roi_compensateestimate_withdraw_day1__ext
总ROI roi_total__ext
总ROI（预估赔付） roi_total_compensateestimate__ext
总ROI（预估赔付+提现） roi_total_compensateestimate_withdraw__ext
次日进程留存率 day2_process_start_radio__ext
次日前台留存率 day2_app_open_radio__ext
累计天数 accumulate_day
修改时间 update_time
excel;
    $data = explode(PHP_EOL, $sql);
    $res = [];
    foreach ($data as $datum) {
        $datum = str_replace("	", " ", $datum);
        $list = explode(' ', $datum);
        if (count($list) <= 1) {
            continue;
        }
        $name = $list[0];
        $key = $list[1];
        $template = <<<tem
'{$key}' => [
    'name'    => '$name',
    'noescape' => true,
    'order_type' => 'desc',
    'display' => '+list,+edit,-search,+detail',
],
tem;
        echo $template . PHP_EOL;

    }
});

routes::cli('test-key', function () {
    $path = DIR_PATH . '/filesystem/test.txt';
    $data = file_get_contents($path);
    preg_match_all("/\'(.*?)\'/is", $data, $match, PREG_SET_ORDER);
    $result = [];
    foreach ($match as $item) {
        $result[$item[1]] = '';
    }
});

routes::cli('use-test', function () {
    $data = 1;
    $fun = function ()use ($data){
        return $data;
    };
    $data++;
    return $fun();
});


routes::cli('es-index', ElasticsearchController::class . '@index');
routes::cli('es-search', ElasticsearchController::class . '@search');
routes::cli('trie', TrieController::class . '@index');
routes::cli('date-', function (){
    $fd = fopen("test.txt",'w+');
    return date('Y-m-d', strtotime('-3 month'));
});
routes::cli('md-reduce', function () {
   $key = '1926861af21d80813433f5a2df909f51';
   $list = [];
   $str = "";
   $lastCharIsNumber = null;
   for ($i=0; $i<strlen($key);$i++) {
       $char = substr($key, $i, 1);
       if (is_null($lastCharIsNumber)) {
           $lastCharIsNumber = is_numeric($char);
           $str .= $char;
           continue;
       }
       //判断是否发生变化
       if (is_numeric($char) == $lastCharIsNumber) {
           //changed
           $str .= $char;
       }else{
           $list[] = $str;
           $str = $char;
       }
       $lastCharIsNumber = is_numeric($char);
   }
    $resultStr = "";
    foreach ($list as $value) {
        if (is_numeric($value)) {

            echo $value . PHP_EOL;
            $resultStr .= base_convert($value, 10, 32);
        }else{
            $resultStr .= $value;
        }
    }
    echo $resultStr;
});
routes::cli('md-test', function () {
    return md5(time().common::rand(10));
});

routes::cli('field', function () {
   $json = <<<json
{

    "store_number": 5,
    "BlockNumber": "5",

    "TxHash": "0xd98d4c6587d198349ad42279294da109c0f6e51ceada3bf2ae57952e02651643",

    "TxMeta": {

      "l1BlockNumber": 31,

      "l1Timestamp": 1679656256,

      "l1MessageSender": "0x0000000000000000000000000000000000000000",

      "queueOrigin": 1,

      "index": 4,

      "queueIndex": 4,

      "rawTransaction": "y9Ts6QAAAAAAAAAAAAAAAEIAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAi6zP9WH95h1ryLbymf+6Vh0hibkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAORmKmM6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADerd6t3q3erd6t3q3erd6t3q0REQAAAAAAAAAAAAAAABXTSq9UJn2318Nng5qvcaAKLGplAAAAAAAAAAAAAAAAFdNKr1QmfbfXw2eDmq9xoAosamUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQ8M8GTdWSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"

    },

    "TxDetail": {

      "nonce": "0x4",

      "gasPrice": "0x0",

      "gas": "0x7a1200",

      "to": "0x4200000000000000000000000000000000000007",

      "value": "0x0",

      "input": "0xcbd4ece900000000000000000000000042000000000000000000000000000000000000100000000000000000000000008baccff561fde61d6bc8b6f299ffba561d2189b90000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000e4662a633a0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000deaddeaddeaddeaddeaddeaddeaddeaddead111100000000000000000000000015d34aaf54267db7d7c367839aaf71a00a2c6a6500000000000000000000000015d34aaf54267db7d7c367839aaf71a00a2c6a6500000000000000000000000000000000000000000000010f0cf064dd5920000000000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",

      "v": "0x0",

      "r": "0x0",

      "s": "0x0",

      "hash": null

    }

  }
json;
   $data = json_decode($json, true);
   foreach ($data as $key => $value) {
       $newKey = preg_replace_callback('/([A-Z]{1})/', function($matches){
           return '_' . strtolower($matches[0]);
       }, $key);
       $newKey = substr($newKey, 1, strlen($newKey));
       if (!is_array($value)) {
           if (gettype($value) == 'integer') {
               $out = <<<template
{$key} int    `json:"{$newKey}" gorm:"type:int"`
template;
               echo $out . PHP_EOL;
           }else{
               $out = <<<template
{$key}    string `json:"{$newKey}"    gorm:"type:varchar(100)"`
template;
               echo $out . PHP_EOL;
           }
       }else{
           foreach ($value as $itemKey => $itemValue) {
               $itemKeyN = ucfirst($itemKey);
               if (gettype($itemValue) == 'integer') {
                   $out = <<<template
{$itemKeyN} int    `json:"{$itemKeyN}" gorm:"type:int"`
template;
                   echo $out . PHP_EOL;
               }else{
                   $out = <<<template
{$itemKeyN}    string `json:"{$itemKeyN}"    gorm:"type:varchar(1000)"`
template;
                   echo $out . PHP_EOL;
               }
           }
       }

   }
});

routes::cli('create-table', function () {
    $template = <<<tem
付费金额
(charge_money)
[charge_money]
(付费需求新增)付费金额（新增设备）
(charge_money_dvmarknew)
[charge_money_dvmarknew]
(付费需求新增)付费金额（召回设备）
(charge_money_dvmarkrecall)
[charge_money_dvmarkrecall]
(付费需求新增)付费APPU
(charge_aepu)
[charge_aepu]
(付费需求新增)付费APPU（新增设备）
(charge_aepu_dvmarknew)
[charge_aepu_dvmarknew]
(付费需求新增)付费APPU（召回设备）
(charge_aepu_dvmarkrecall)
[charge_aepu_dvmarkrecall]
(付费需求新增)
tem;

    $list = explode('(付费需求新增)', $template);
    foreach ($list as $value) {
        $itemList = explode(PHP_EOL, $value);
        if (count($itemList)<=1) {
            continue;
        }
        $name = $itemList[0];
        preg_match('/\((.*?)\)/is', $itemList[1], $match);
        $itemTemplate = <<<EOL
 '{$match[1]}' => [
            'name'    => '{$name}',
            'type'    => 'text',
            'order_type' => 'desc',
            'display' => '+list,+edit,-search,+detail',
        ],
EOL;
        echo $itemTemplate . PHP_EOL;
    }
});

routes::cli('guzz', function () {
    for ($i=0; $i<=10000; $i++) {
        $res = http::requestByGuzzleHttp('https://www.baidu.com', []);
        echo memory_get_usage() . PHP_EOL;
        echo $i . PHP_EOL;
    }
});

routes::cli('account-test', function (){
    for ($i = 0; $i < 10000; ++$i) {
        echo memory_get_usage().PHP_EOL;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, 'https://account.ludashi.com/api/User/information');
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT_MS, 2000);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        $result = curl_exec($curl);
        $errMsg = curl_error($curl);
        curl_close($curl);
        if ($errMsg) {
            echo $errMsg.PHP_EOL;
        }

        // echo $result.PHP_EOL;
    }
});

routes::cli('importData', function (excel $excel) {
    ini_set('memory_limit', '1556M');
   $nowork = <<<sql
CREATE TABLE `ba_nowork` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `type` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '类别:opt0=病假,opt1=休整期,opt2=歇工待业,opt3=工资清零',
  `uid` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '姓名',
  `work_type` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '用工类别:opt0=合同制员工,opt1=规范劳务派遣业务外包工',
  `department` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '三定单位',
  `unit` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '三定岗位',
  `join_date` date DEFAULT NULL COMMENT '开始日期',
  `leave_date` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '结束日期',
  `leave_date_arr` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '请假日期',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='非工作';
sql;
   $homeSql = <<<sql
CREATE TABLE `ba_homeproject` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `type` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '类别:opt0=原基地二线,opt1=项目后期基地劳动,opt2=临时劳动,opt3=后勤值班',
  `location` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '工作地点:opt0=郑州基地,opt1=濮阳基地,opt2=南阳基地',
  `uid` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '姓名',
  `work_type` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '用工类别:opt0=合同制员工,opt1=规范劳务派遣业务外包工',
  `department` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '所在部门',
  `unit` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '岗位名称',
  `position` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '职位',
  `join_date` date DEFAULT NULL COMMENT '开始日期',
  `leave_date` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '结束日期',
  `leave_date_arr` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '请假日期',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='基地工作';
sql;
   $newProject = <<<sql
CREATE TABLE `ba_newproject` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `project` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '项目名称',
  `location` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '项目所在地区:opt0=新疆青海西藏等艰苦地区,opt4=其他地区',
  `uid` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '员工姓名',
  `team` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '班组:opt0=项目组,opt1=队领导,opt2=其他管理及服务,opt3=施工组,opt4=仪器组,opt5=测量组,opt6=表层调查组,opt7=信息组,opt8=放线班,opt9=钻井班,opt10=下药班,opt11=爆炸班,opt12=可控震源组,opt13=工农组,opt14=清线组,opt15=司机班（自有车辆）,opt16=机械修理组,opt17=警卫班,opt18=炊事班,opt19=后勤组,opt20=其他班组和人员',
  `work` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '项目岗位',
  `position` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '职位',
  `unit` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '施工单位',
  `three_unit` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '三定单位',
  `three_work` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '三定岗位',
  `work_type` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '用工类别:opt0=合同制员工,opt1=规范劳务派遣业务外包工',
  `join_date` date DEFAULT NULL COMMENT '进入项目时间',
  `leave_date` date DEFAULT NULL COMMENT '离开项目时间',
  `leave_date_arr` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '项目中请假日期',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='业务项目';
sql;
   $baseSql = <<<sql
CREATE TABLE `ba_baseproject` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `type` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '类别:opt0=原基地二线,opt1=项目后期基地劳动,opt2=临时劳动,opt3=后勤值班',
  `location` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '工作地点:opt0=郑州基地,opt1=濮阳基地,opt2=南阳基地',
  `uid` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '姓名',
  `work_type` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '用工类别:opt0=合同制员工,opt1=规范劳务派遣业务外包工',
  `department` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '所在部门',
  `unit` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '岗位名称',
  `join_date` date DEFAULT NULL COMMENT '开始日期',
  `leave_date` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '结束日期',
  `leave_date_arr` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '请假日期',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='基地工作';
sql;
   $otherSql = <<<sql
CREATE TABLE `ba_otherproject` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `type` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '类别',
  `uid` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '姓名',
  `work_type` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '用工类别:opt0=合同制员工,opt1=规范劳务派遣业务外包工',
  `department` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '三定单位',
  `unit` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '三定岗位',
  `join_date` date DEFAULT NULL COMMENT '开始日期',
  `leave_date` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '结束日期',
  `leave_date_arr` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '请假日期',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='其他';
sql;
   $config = [
       '业务项目' => $newProject,
       '培训实习' => $baseSql,
       '基地工作' => $homeSql,
       '非工作' => $nowork,
       '其他' => $otherSql,
   ];
   $excelData = $excel->read_excel(DIR_PATH . 'filesystem/修改.xlsx');
   foreach ($excelData as $index =>  $datum) {
       $itemMap = [];
       $itemData =  $datum['data'];
       $field = [];
       $itemExcelData = [];
       foreach ($itemData as $key => $itemDatum) {
           if ($key == 0) {
               $field = $itemDatum;
           }
           $mapData = [];
           foreach ($itemDatum as $itemIndex => $item) {
               $mapData[$field[$itemIndex]] = $item;
           }
           $itemExcelData[] = $mapData;
       }
       $excelData[$index] = $itemExcelData;
   }
   $index = 0;
   foreach ($config as $name => $sql) {
       $data = $excelData[$index];
       $index++;
       $str = '';
       preg_match_all('/`(.*?)` (.*?) (.*?),\n/u', $sql, $matchs, PREG_SET_ORDER);
       preg_match_all('/CREATE TABLE `(.*?)`/u', $sql, $tableMatch, PREG_SET_ORDER);
       $tableName = $tableMatch[0][1];
       $map = [];
       foreach ($matchs as $match) {
           $field = $match[1];
           $type = (strrpos($match[2], 'int') !== false) ? 'int' : 'string';
           preg_match_all("/COMMENT '(.*?)'/u", $match[3], $commentMatch, PREG_SET_ORDER);
           $comment = empty($commentMatch[0][1]) ? '' : $commentMatch[0][1];
           $str .= " * @property {$type} \${$field} $comment" . PHP_EOL;
           $keys = explode(':', $comment);
           if (count($keys)>1) {
               $localMap = [];
               $opts = explode(',', $keys[1]);

               foreach ($opts as $opt) {
                   $opt = explode('=', $opt);
                   if (count($opt)<=1) {
                       print_r($opt);die();
                   }
                   $localMap[$opt[1]] = $opt[0];
               }
               $map[$keys[0]] = [
                   'field' => $field,
                   'config' => $localMap
               ];
           }else{
               $map[$keys[0]] = [
                   'field' => $field,
                   'config' => []
               ];
           }
       }
       $insertData = [];
       foreach ($data as $datum) {
           $itemData = [];
           foreach ($datum as $key => $value) {
               if (empty($map[$key])){
                   continue;
               }
               $mapConfig = $map[$key];
               $itemData[$map[$key]['field']] = $value;
               if (!empty($mapConfig['config'])) {
                   if (!empty($mapConfig['config'][$value])) {
                       $itemData[$map[$key]['field']] = $mapConfig['config'][$value];
                   }
               }
           }
           $insertData[] = $itemData;
       }
       print_r($insertData);
   }


});



